<template>
    <!-- 智能模型算法管理 -->
    <div class="model-manage">
        <div class="mm-panel-wrapper-left">
            <Tree ref="leftTreeRef" :isOwnAccount="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_1"
                :folderMenu="right_menuList.rightMenuList_3" :fileMenu="right_menuList.rightMenuList_4"
                :treeData="ownTreeData" :currentNodeKey="currentNodeKey" :defaultExpandedKeys="defaultExpandedKeys"
                @handleAddNode="handleAddModel" @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick"
                @nodeDelete="handleNodeDelete" @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
            </Tree>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-panel-wrapper-right">
            <div class="padding20">
                <!-- 算法 -->
                <div>
                    <div class="mm-panel-title mb-10">
                        算法基本信息
                        <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                    </div>
                    <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="名称" prop="name">
                                    <el-input v-model="itemForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="创建日期" prop="createTime">
                                    <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" v-model="itemForm.description"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- 算法版本 -->
                <div>
                    <div class="mm-panel-title mb-10">
                        算法基本信息
                        <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                    </div>
                    <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="名称" prop="name">
                                    <el-input v-model="itemForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="版本号" prop="name">
                                    <el-input v-model="itemForm.name"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="创建日期" prop="createTime">
                                    <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="基准版本" prop="name">
                                    <div class="flex">
                                        <el-input v-model="itemForm.name"></el-input>
                                        <el-button type="primary" @click="handleSave">选择</el-button>
                                    </div>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="描述" prop="description">
                            <el-input type="textarea" v-model="itemForm.description"></el-input>
                        </el-form-item>
                        <el-form-item label="镜像选择" prop="name">
                            <div class="flex">
                                <el-input v-model="itemForm.name"></el-input>
                                <el-button type="primary" @click="handleSave">选择</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="输入样本集选择" prop="name">
                            <div class="flex">
                                <el-input v-model="itemForm.name"></el-input>
                                <el-button type="primary" @click="handleSave">选择</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="输出样本集选择" prop="name">
                            <div class="flex">
                                <el-input v-model="itemForm.name"></el-input>
                                <el-button type="primary" @click="handleSave">选择</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                    <div style="height: 40px;">
                        <el-button style="float: right;margin-left: 10px;" class="ml-10" type="primary" @click="handleSave">发布</el-button>
                        <el-button style="float: right;" class="ml-10" type="primary"
                            @click="handleSave">在线开发</el-button>
                        <el-button style="float: right;margin-left: 10px;" class="ml-10" type="primary"
                            @click="handleSave">开发容器启动/停止</el-button>
                    </div>
                    <div class="flex">
                        <div style="width: 50%">
                            <div class="mm-panel-title mb-10">
                                算法开发环境状态信息
                            </div>
                            <div
                                style="border: 1px solid var(--ui-border-color-split);padding-top: 20px;padding-right: 20px;padding-bottom: 20px;">
                                <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                                    <el-form-item label="运行状态" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="资源占用" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="开发状态" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </div>
                        <div style="width: 50%">
                            <div class="mm-panel-title mb-10">
                                服务发布状态
                            </div>
                            <div
                                style="border: 1px solid var(--ui-border-color-split);padding-top: 20px;padding-right: 20px;padding-bottom: 20px;">
                                <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                                    <el-form-item label="服务状态" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="服务地址" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="接口说明" prop="name">
                                        <el-input v-model="itemForm.name"></el-input>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog title="新增" :visible.sync="openDialog" width="800px" append-to-body>
            <div></div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary">确 定</el-button>
                <el-button @click="openDialog = false">取 消</el-button>
            </div>
        </el-dialog>
        <AddOrUpdateFolder v-if="isAddOrUpdateFolder" ref="addOrUpdateFolderRef" @refresh="getList"></AddOrUpdateFolder>
        <AddOrUpdateModel v-if="isAddOrUpdateModel" ref="addOrUpdateModelRef" @refresh="getList"></AddOrUpdateModel>
    </div>
</template>

<script>
import { mapState } from "vuex";
import {
    addModel,
    deleModel,
    getSelfModelTree,
    moveTreeNodeOrder,
} from "@/api/myspace/model-manage-tool/model-manage";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";

export default {
    data() {
        return {
            rules: {
                name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
            },
            itemForm: {
                name: "xxxxxx", //名称
                createTime: "2025-09-01 10:10:10",
                description: "xxxxxxxxxxxxxxxxxxxxxx", //描述
            },
            openDialog: false,
            loading: false,
            tableList: [
                {
                    name: "xxxxx",
                    state: "运行中",
                    occupancy: "CPU:1/2 内存:1/2",
                    description: "针对xxx生成的样本数据",
                    createTime: "2021-01-01 10:10:10",
                }
            ],
            queryParams: { // 查询参数
                pageNum: 1,
                pageSize: 10,
                name: "",
                modelId: "",
                folderId: "",
            },
            isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
            isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
            isFolder: false, // 是否展示文件夹详情
            isFile: false, // 是否展示文件详情
            isModel: false, //是否是模型详情
            isModelGroupDetail: false, // 是否展示模型组详情,
            selectedNodeInfo: {}, // 当前选中节点的信息
            ownTreeData: [], // 本账户模型列表
            currentNodeKey: 0, // 当前选中节点的key
            defaultExpandedKeys: [] // 默认展开的节点
        };
    },
    components: {
        Tree,
        AddOrUpdateModel,
        AddOrUpdateFolder,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
            expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
        }),
    },
    async created() {
        await this.getList();
        this.currentNodeKey = this.selectedNodeId;
        this.defaultExpandedKeys = this.expandedNodeIds;
        this.$nextTick(() => {
            this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        })
    },
    mounted() {

    },
    methods: {
        // 保存
        handleSave() {

        },
        handleDevelopment() {
            const iframeSrc = 'http://192.168.1.109:3000/#/home/project';
            // 生成唯一标识符
            const paramId = 'param_' + new Date().getTime();

            // 将参数存储到 sessionStorage
            sessionStorage.setItem(paramId, iframeSrc);

            // 在 URL 中传递标识符
            window.open(`/notebook/jupyter?paramId=${paramId}`, '_blank');
        },
        handleEdit() {

        },
        handleCommand(command) {
            this.$message('click on item ' + command);
            switch (command) {
                case 'edit':
                    this.handleEdit();
                    break;
                case 'development':
                    this.handleDevelopment();
                    break;
            }
        },
        //新增
        handleAdd() {
            this.openDialog = true;
        },
        //查询
        handleQuery() {

        },
        //重置搜索条件
        resetQuery() {

        },
        async getList(newNodeId) {
            await getSelfModelTree().then((res) => {
                if (res.code == 200 && Array.isArray(res.data)) {
                    this.ownTreeData = res.data[0].commonTreeList;
                    // this.nodeClick(
                    //   newNodeId ? this.recurNodeForTarget(this.ownTreeData, newNodeId) :
                    //     this.selectedNodeId ? this.recurNodeForTarget(this.ownTreeData, this.selectedNodeId) :
                    //       this.ownTreeData[0])

                    const targetId = newNodeId || this.selectedNodeId;
                    const targetnode = targetId ? this.recurNodeForTarget(this.ownTreeData, targetId) : this.ownTreeData[0];
                    this.nodeClick(targetnode);
                }
            });
        },
        // 递归获取当前树节点
        recurNodeForTarget(nodeArr, id) {
            for (let i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].id == id) {
                    return nodeArr[i];
                } else {
                    if (nodeArr[i].children && nodeArr[i].children.length > 0) {
                        let node = this.recurNodeForTarget(nodeArr[i].children, id);
                        if (node) {
                            return node;
                        }
                    }
                }
            }
        },
        // 新增文件夹
        handleAddOrUpdateFolder(sign, node) {
            this.isAddOrUpdateFolder = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateFolderRef"].init(
                    sign,
                    node,
                    this.ownTreeData,
                    "account"
                );
            });
        },
        // 新增数据模型
        handleAddModel(node) {
            this.isAddOrUpdateModel = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateModelRef"].init(undefined, node);
            });
        },
        // 点击树节点，右侧展示详细信息
        nodeClick(node) {
            if (node == undefined) {
                return;
            }
            this.selectedNodeInfo = node;
            this.currentNodeKey = node.id;
            this.$nextTick(() => {
                this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
            })
            this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", { moduleName: 'model', id: node.id })
            if (!node.data) return;

            if (node.type == 0) {
                // 点击的文件夹
                this.isFolder = true;
                this.isModel = false;
                this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", { moduleName: 'model', idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])) })
            } else {
                // 点击的文件
                this.isFolder = false;
                this.isFile = true;
                this.isModel = true;
            }
        },
        /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
        handleNodeDelete(node) {
            this.$confirm(
                `确定删除${node.type == 0 ? "目录" : "数据模型"}  ${node.data.modelName
                } ?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    customClass: "message-box-style",
                    type: "warning",
                }
            )
                .then(() => {
                    deleModel(node.id).then((response) => {
                        console.log(response);
                        if (response.code == 200) {
                            this.$message.success(
                                this.$toolHandle.getI18nName(
                                    this.$zh.setup.responseText,
                                    this.$en.setup.responseText,
                                    this.$i18n.locale,
                                    "success"
                                )
                            );
                            if (node.id == this.currentNodeKey) {
                                this.isFolder = false;
                                this.isModel = false;
                            }
                            this.getList();
                        }
                    });
                })
                .catch(() => { });
        },
        /**
         * 树节点复制事件的回调
         * @param node 被复制的节点
         */
        handleCopyFile(node) {
            addModel({
                modelName: node.data.modelName + " Copy",
                modelEnglishName: node.data.modelEnglishName + " Copy",
                modelAlias: node.data.modelAlias + " Copy",
                parentId: node.data.parentId,
                nodeType: node.type, // 0表示文件夹，1表示文件
                categoryLabel: node.data.categoryLabel,
                modelResolution: node.data.modelResolution,
                modelDescription: node.data.modelDescription,
                modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
                userId: node.data.userId,
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            moveTreeNodeOrder({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 点击菜单项触发的事件
        handleMenuClick(menu, node) {
            switch (menu.name) {
                case "新增数据模型":
                case "新增装备模型":
                    this.handleAddModel(node);
                    break;
                case "新增分类":
                    this.handleAddOrUpdateFolder("add");
                    break;
                case "添加子目录":
                    this.handleAddOrUpdateFolder("add", node);
                    break;
                case "编辑":
                    this.handleAddOrUpdateFolder("edit", node);
                    break;
                case "复制":
                    // 文件的复制
                    this.handleCopyFile(node);
                    break;
                case "删除":
                    // 文件夹/文件的删除
                    this.handleNodeDelete(node);
                    break;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.model-manage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;

    .mm-panel-wrapper-left {
        width: 300px;
        height: 100%;
        flex-grow: 0;
        flex-shrink: 0;
        display: flex;
        position: relative;
        padding: 0 10px;
    }

    .mm-divider {
        width: 1px;
        height: auto;
        flex-grow: 0;
        position: relative;
        align-self: stretch;
        background-color: var(--ui-border-color-split);
    }

    .mm-panel-wrapper-right {
        width: 256px;
        height: 100%;
        min-width: 0px;
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        position: relative;
        overflow: auto;
    }
}

.padding20 {
    padding: 20px;
    width: 100%;
}
</style>
